<!-- src/views/CallbackView.vue -->
<template>
  <div class="callback-container">
    <div v-if="loading">正在处理授权...</div>
    <div v-if="error" class="error-message">{{ error }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getToken } from '@/services/api';

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const error = ref(null);

onMounted(async () => {
  const code = route.query.code;
  const clientId = route.query.state || 'default';

  if (!code) {
    error.value = '未收到授权码';
    loading.value = false;
    return;
  }

  try {
    const response = await getToken(code, clientId);
    const token = response.data;

    // 存储令牌
    localStorage.setItem('baidu_access_token', token.baiduAccessToken);
    localStorage.setItem('baidu_refresh_token', token.baiduRefreshToken);
    localStorage.setItem('expires_at', new Date(token.expiresAt).getTime());

    router.push({ name: 'Dashboard' });
  } catch (err) {
    console.error('获取令牌失败', err);
    error.value = '授权失败：' + err.message;
    loading.value = false;
  }
});
</script>